import { factory, primaryKey } from "@mswjs/data";
import { http, delay, HttpResponse } from "msw";
// import { nanoid } from '@reduxjs/toolkit'
export interface Post {
  id: string;
  name: string;
}

const db = factory({
  post: {
    id: primaryKey(String),
    name: String,
  },
});

// 初始化数据
// 创建数据后就不管了么
[
  "A sample post",
  "A post about RTK Query",
  "How to randomly throw errors, a novella",
].forEach((name, idx) => {
  db.post.create({ id: `post-${idx}`, name });
});

// console.log(db.post.count());
// console.log(db.post.toHandlers("rest"));

export const handlers = [
  http.get("https://api.example.com/user", () => {
    return HttpResponse.json({
      id: "abc-123",
      firstName: "John",
      lastName: "Maverick",
    });
  }),
    http.get("/posts/delay", async () => {
    // Await a random realistic server response time.
    console.log("delay all posts")
    await delay(3000);
    const allPosts = db.post.getAll()
    return HttpResponse.json(allPosts);
  }),
  http.put("/posts/delay/:postId", async ({ request, params }) => {
    // Await a random realistic server response time.
    await delay(3000);

    const { postId } = params;
    const nextPost = await request.json();

    if (!nextPost) {
      console.error("nextPost is null or undefined");
      return; // 或者你可以返回一个错误响应
    }

    const newPost = nextPost as Post;
    console.log('Updating post "%s" with:', postId, nextPost);

    const updatedPost = db.post.update({
      // Query for the entity to modify.
      where: {
        id: {
          equals: postId as string,
        },
      },
      // Provide partial next data to be
      // merged with the existing properties.
      data: {
        // Specify the exact next value.
        name: newPost.name,
      },
    });

    return HttpResponse.json(updatedPost);
  }),

  ...db.post.toHandlers("rest"), // https://www.npmjs.com/package/@mswjs/data#tohandlers
] as const;

// GET /users/:id (where "id" is your model's primary key), returns a user by ID;
// GET /users, returns all users (supports pagination);
// POST /users, creates a new user;
// PUT /users/:id, updates an existing user by ID;
// DELETE /users/:id, deletes an existing user by ID;
